<template>
  <PageLayout full :page-style="pageStyle">
    <template #header>
      <HeaderLayout show-back title="固件升级">{{ runingUpdateType }}</HeaderLayout>
    </template>

    <view class="update-view">
      <view class="update-box">
        <view class="update-content">
          <view class="update-title">Wi-Fi Profile</view>
          <view class="version">家电端版本: {{ profileVersion }}</view>
          <view class="version">服务端版本: {{ serverProfileVersion }}</view>
        </view>
        <view
          class="update-btn"
          :class="{ latestText: !serverProfileVersion || isLatestProfile }"
          @click="upgradeProfileVersionFun"
        >
          {{ profileText }}
        </view>
      </view>

      <view class="update-box" v-for="(item, index) in firmwareVersionList" :key="index">
        <view class="update-content">
          <view class="update-title">{{ item.name }}</view>
          <view class="version">家电端版本: {{ item.localVersion }}</view>
          <view class="version">服务端版本: {{ item.serverVersion }}</view>
        </view>
        <view
          class="update-btn"
          :class="{ latestText: !item.serverVersion || item.serverVersion === item.localVersion }"
          @click="upgradeFirmwareVersionFun(item)"
        >
          {{ wifiMcuText(item) }}
        </view>
      </view>
    </view>

    <OtaModalView
      :show="profileLoad && wifiMcuLoad"
      :mcu-status="mcuStatus"
      :upgrade-name="upgradeName"
      :upgrading="isRuningUpdate"
      :upgrade-type="runingUpdateType"
      :upgrade-sucess-profile="upgradeSucessProfile"
      :upgrade-fail-profile="upgradeFailProfile"
      @sucess-profile="upgradeSucessProfile = false"
      @fail-profile="upgradeFailProfile = false"
      @upgrade-sucess="upgradeSucessFun"
      @upgrade-runing="upgradeRuningFun"
    ></OtaModalView>
  </PageLayout>
</template>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import OtaModalView from '@/pages/appliance/BIWD/otaModalView/otaModalView.vue'

import { onLoad } from '@dcloudio/uni-app'
import { getProfileVersion, getFirmwareVersion, upgradeProfileVersion, upgradeFirmwareVersion } from '@/api/biwd'
import { actionDebounce } from '@/utils/mpHelper'
import { useWebsocketListener } from '@/utils/socket/WebSocketHandlerImp'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import type { WS } from '@/utils/socket/types'
import { UPGRADE_MCUSTATUS } from '@/constants/WDCommand'
import { getAllSetting } from '@/api/appliance'

const pageStyle = {
  backgroundColor: '#f4f4f6',
}

let callApiTimer: number | undefined
let count = 0

const haId = ref('')
const runingUpdateType = ref('') // 升级类型
const isRuningUpdate = ref(false) //是否正在升级
const mcuStatus = ref(0)
const upgradeName = ref('')

const isLatestProfile = computed(() => profileVersion.value === serverProfileVersion.value)
const profileText = computed(() => {
  if (runingUpdateType.value === 'Profile' && isRuningUpdate.value) {
    return '升级中...'
  } else if (!serverProfileVersion.value || isLatestProfile.value) {
    return '已是最新版本'
  } else {
    return '立即升级'
  }
})
function wifiMcuText(item: FirmwareVersionType) {
  if (item.hwcode === '56') {
    if (runingUpdateType.value === 'Wifi' && isRuningUpdate.value) {
      return '升级中...'
    } else if (!item.serverVersion || item.serverVersion === item.localVersion) {
      return '已是最新版本'
    } else {
      return '立即升级'
    }
  } else if (item.hwcode === 'WS5054BC1C_01') {
    if (runingUpdateType.value === 'MCU' && isRuningUpdate.value) {
      return '升级中...'
    } else if (!item.serverVersion || item.serverVersion === item.localVersion) {
      return '已是最新版本'
    } else {
      return '立即升级'
    }
  }
}

onLoad((query: any) => {
  haId.value = query?.haId
  getSettingsFun()
  getProfileVersionFun()
  getFirmwareVersionFun()
  listenMessages()
})

/**
 * 获取Wi-Fi Profile
 */
const profileVersion = ref('')
const serverProfileVersion = ref('')
const serverProfileUrl = ref('')
const profileLoad = ref(false)
const upgradeSucessProfile = ref(false)
const upgradeFailProfile = ref(false)
async function getProfileVersionFun(type?: string) {
  const res = await getProfileVersion(haId.value)
  profileVersion.value = res.data.profileversion
  serverProfileVersion.value = res.data.serverprofileversion.version
  serverProfileUrl.value = res.data.serverprofileversion.url
  profileLoad.value = true
  if (type === 'judge') {
    if (Number(profileVersion.value) === Number(serverProfileVersion.value)) {
      upgradeSucessProfile.value = true
      upgradeFailProfile.value = false
      isRuningUpdate.value = false
      clearInterval(callApiTimer)
    } else if (Number(profileVersion.value) !== Number(serverProfileVersion.value) && count == 3) {
      isRuningUpdate.value = false
      upgradeFailProfile.value = true
      isRuningUpdate.value = false
      clearInterval(callApiTimer)
    }
  }
}
/**
 * 升级Wi-Fi Profile
 */
const upgradeProfileVersionFun = actionDebounce({
  call: async () => {
    let submitData = {
      url: serverProfileUrl.value,
      type: 'PROFILE',
    }
    const res = await upgradeProfileVersion(haId.value, submitData)
    if (res.code !== 0) return
    runingUpdateType.value = 'Profile'
    upgradeName.value = 'WIFI Profile'
    isRuningUpdate.value = true
    callApiTimer = setInterval(() => {
      count++
      getProfileVersionFun('judge')
    }, 30000)
  },
})

/**
 * 获取wifi固件和mcu固件信息
 */
type FirmwareVersionType = {
  name: string
  localVersion: string
  upgradingVersion: string
  hwcode: string
  changeLog: string
  serverVersion: string
  url: string
  upgradeflag: number
  pid: string
}
const firmwareVersionList = ref<FirmwareVersionType[]>([])
const wifiMcuLoad = ref(false)
async function getFirmwareVersionFun() {
  const res = await getFirmwareVersion(haId.value)
  let versionList = res.data || []
  firmwareVersionList.value = []
  versionList.forEach((item) => {
    if (item.upgradingVersion !== '' && item.upgradingVersion !== '0') {
      isRuningUpdate.value = true
      runingUpdateType.value = item.hwcode === '56' ? 'Wifi' : 'MCU'
      upgradeName.value = item.hwcode === '56' ? 'Wifi 固件' : 'MCU 固件'
    }
    firmwareVersionList.value.push({
      name: item.hwcode === '56' ? 'Wi-Fi 固件' : 'MCU 固件',
      localVersion: item.version,
      upgradingVersion: item.upgradingVersion,
      hwcode: item.hwcode,
      changeLog: item.serverVersion.changeLog,
      serverVersion: item.serverVersion.version,
      url: item.serverVersion.url,
      upgradeflag: item.serverVersion.upgradeflag,
      pid: item.pid,
    })
  })
  wifiMcuLoad.value = true
}
/**
 * 升级wifi固件或mcu固件
 */
const upgradeHwcode = ref('')
const upgradeFirmwareVersionFun = actionDebounce({
  call: async (item: FirmwareVersionType) => {
    let submitData = {
      url: item.url,
      pid: item.pid,
      hwcode: item.hwcode,
      version: item.serverVersion,
    }
    const res = await upgradeFirmwareVersion(haId.value, submitData)
    if (res.code !== 0) return
    isRuningUpdate.value = true
    runingUpdateType.value = item.hwcode === '56' ? 'Wifi' : 'MCU'
    upgradeHwcode.value = item.hwcode
    upgradeName.value = item.name
  },
})

/**
 * 升级成功
 * @param value
 */
function upgradeSucessFun(value: boolean) {
  if (!value && runingUpdateType.value === 'Profile') return
  getFirmwareVersionFun()
}

/**
 * 正在升级中
 * @param value
 */
function upgradeRuningFun(value: boolean) {
  isRuningUpdate.value = value
}

/**
 * 监听
 */
function listenMessages() {
  useWebsocketListener(WebsocketManager.instance.oemWebsocket, (msg: WS.Message) => {
    if (msg.haId !== haId.value || !Array.isArray(msg.items)) return
    msg.items.forEach((item) => {
      console.error('handleMsg', item)
      if (item.key === UPGRADE_MCUSTATUS) {
        console.error('mcuStatus', item.value)
        mcuStatus.value = Number(item.value)
      }
    })
  })
}

/**
 * 加载settings接口
 */
async function getSettingsFun() {
  const res = await getAllSetting(haId.value)
  let settings = res.data.settings || []
  settings.forEach((item) => {
    if (item.key === UPGRADE_MCUSTATUS) {
      mcuStatus.value = Number(item.value)
    }
  })
}
</script>

<style lang="less">
.disabled {
  opacity: 0.4;
  pointer-events: none;
}
.latestText {
  color: #b4b9c3 !important;
  pointer-events: none;
}
// 显示内容
.update-view {
  margin-top: 16rpx;
  .update-box {
    background-color: #fff;
    box-sizing: border-box;
    font-family: PingFang SC;
    font-style: normal;
    margin-bottom: 108rpx;
    .update-content {
      height: 230rpx;
      padding: 26rpx 32rpx;
      box-sizing: border-box;
      .update-title {
        font-size: 32rpx;
        font-weight: 500;
        color: var(--dack-color);
        margin-bottom: 8rpx;
      }
      .version {
        font-size: 28rpx;
        font-weight: 400;
        color: var(--dack-color);
        opacity: 0.8;
      }
    }
    .update-btn {
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 32rpx;
      font-weight: 500;
      color: var(--primary-color);
      border-top: 1rpx solid #ecece9;
    }
  }
}
</style>
